package service

import (
	"context"
	"dy/internal/api/store"
	"dy/internal/models"
	"dy/pkg/util"
	"errors"
)

type CommentSrv interface {
	Action(ctx context.Context, param map[string]interface{}) (int, error)
	List(ctx context.Context, videoId int) ([]map[string]interface{}, error)
}

type commentService struct {
	store store.Factory
}

func (u *commentService) Action(ctx context.Context, param map[string]interface{}) (int, error) {
	var dyComment *models.DyComment
	err := util.StructTo(&param, &dyComment)
	if err != nil {
		return 0, err
	}

	if param["action_type"].(int) == 1 {
		_, err = u.store.Comment().Create(ctx, dyComment)
		if err != nil {
			return 0, err
		}
		return dyComment.Id, nil
	} else if param["action_type"].(int) == 2 {
		comment, flag, err := u.store.Comment().Get(ctx, &models.DyComment{Id: dyComment.Id})
		if err != nil {
			return 0, err
		}
		if !flag {
			return 0, nil
		}

		_, err = u.store.Comment().Del(ctx, comment.Id)
		if err != nil {
			return 0, err
		}
	} else {
		return 0, errors.New("wrong action_type")
	}

	return dyComment.Id, nil
}

func (u *commentService) List(ctx context.Context, videoId int) ([]map[string]interface{}, error) {
	search := map[string]interface{}{}
	if videoId != 0 {
		search["video_id"] = videoId
	}

	list, _, err := u.store.Comment().Find(ctx, search, "add_time", "")
	if err != nil {
		return nil, err
	}
	result := make([]map[string]interface{}, 0)

	for _, element := range list {
		dyUser, flag, err := u.store.User().Get(ctx, &models.DyUser{Id: element.UserId})
		if !flag {
			return nil, errors.New("the user is not exist")
		}
		if err != nil {
			return nil, err
		}

		_, followCount, err := u.store.Relation().Find(ctx, map[string]interface{}{"user_id": dyUser.Id}, "add_time", "")
		if err != nil {
			return nil, err
		}
		_, followerCount, err := u.store.Relation().Find(ctx, map[string]interface{}{"follow_id": dyUser.Id}, "add_time", "")
		if err != nil {
			return nil, err
		}
		_, isFollow, err := u.store.Relation().Get(ctx, &models.DyUserRelation{UserId: videoId, FollowId: dyUser.Id})
		if err != nil {
			return nil, err
		}

		user := map[string]interface{}{
			"id":             dyUser.Id,
			"name":           dyUser.Name,
			"follow_count":   followCount,
			"follower_count": followerCount,
			"is_follow":      isFollow,
		}

		comment := map[string]interface{}{
			"id":          element.Id,
			"user":        user,
			"content":     element.Content,
			"create_date": element.AddTime,
		}

		result = append(result, comment)
	}

	return result, nil
}

func NewCommentService(s *service) CommentSrv {
	return &commentService{
		store: s.store,
	}
}
